package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.robot.admin.client.CouponClient;
import com.robot.admin.client.MerchantClient;
import com.robot.admin.pojo.client.Coupon;
import com.robot.admin.pojo.client.Store;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 优惠券
 *
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/coupon")
public class CouponController {

    @Autowired
    private CouponClient couponClient;

    @Autowired
    private MerchantClient merchantClient;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * body传的是String而不是map,所以nullValue.equals(memberId)代替memberId==null的判断
     */
    private final String nullValue = "null";

    /**
     * 优惠券列表-条件查询
     *
     * @param searchMap 查询件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "findCouponsBySearch/{page}/{size}", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public Result findCouponsBySearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("searchMap=" + searchMap);

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(couponClient.thirdFindCouponsBySearch(searchMap, page, size)));
    }

    /**
     * 根据ID查询优惠券详情
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "findCouponById/{id}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public Result findCouponById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("id=" + id);

        Coupon couponInDb = JSON.parseObject(couponClient.thirdFindCouponById(id), Coupon.class);
        logger.info("couponInDb=" + couponInDb);
        if (couponInDb == null) {
            return new Result(StatusCode.ERROR, "该优惠券不存在");
        }
        if (couponInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR, "该优惠券已被删除");
        }
        return new Result(StatusCode.SUCCESS_QUERY, couponInDb);
    }

    /**
     * 增加优惠券
     *
     * @param searchMap
     */
    @RequestMapping(value = "addCoupon", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public Result addCoupon(@RequestBody String searchMap) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("searchMap=" + searchMap);

        JSONObject jsonObject = JSONObject.parseObject(searchMap);
        //会员id
        String memberId = jsonObject.get("memberId") + "";
        //body传的是String而不是map,所以nullValue.equals(memberId)代替memberId==null的判断
        if ("".equals(memberId) || nullValue.equals(memberId)) {
            logger.info("会员id不存在");
        } else {
            //判断会员是否存在
            logger.info("会员id存在");
        }
        //公司id
        String companyId = jsonObject.get("companyId") + "";
        if ("".equals(companyId) || nullValue.equals(companyId)) {
            logger.info("公司id不存在");
        } else {
            //判断公司是否存在
            logger.info("公司id存在");
        }
        //店铺/商家id
        String storeId = jsonObject.get("storeId") + "";
        //店铺/商家名字
        String storeName = "";
        if ("".equals(storeId) || nullValue.equals(storeId)) {
            logger.info("店铺/商家id不存在");
        } else {
            //判断店铺/商家是否存在
            //店铺存在,则更新商家名字
            logger.info("店铺/商家id存在");
        }

        //面值
        String priceObject = jsonObject.get("price") + "";
        if ("".equals(priceObject) || nullValue.equals(priceObject)) {
            return new Result(StatusCode.ERROR, "面值必填");
        }
        Double price = Double.valueOf(jsonObject.get("price") + "");
        //面值必须大于0
        if (price <= 0) {
            return new Result(StatusCode.ERROR, "面值必须大于0");
        }

        //使用条件 json值(price和stores)
        JSONObject usageCondition = jsonObject.getJSONObject("usageCondition");
        logger.info("使用条件" + ("".equals(usageCondition)));
        logger.info("使用条件" + (null == usageCondition));
        logger.info("使用条件" + (nullValue.equals(usageCondition)));
        if ("".equals(usageCondition) || null == usageCondition) {
            return new Result(StatusCode.ERROR, "使用条件必填");
        }
        //判断使用条件中价格必须存在且大于等于0
        String priceTemp = usageCondition.get("price") + "";
        if ("".equals(priceTemp) || nullValue.equals(priceTemp)) {
            return new Result(StatusCode.ERROR, "使用条件中price必填");
        }
        Double usageConditionPrice = Double.valueOf(priceTemp);
        if (usageConditionPrice < 0) {
            return new Result(StatusCode.ERROR, "使用条件中price不能小于0");
        }
        //判断使用条件中店铺是否存在
        String usageConditionStores = (String) usageCondition.get("stores");
        if (usageConditionStores == null || "".equals(usageConditionStores)) {
//            return new Result(StatusCode.ERROR, "使用条件中store必填");
        } else {
            String[] stores = usageConditionStores.split(",");
            for (int i = 0; i < stores.length; i++) {
                //判断店铺ID是否存在
                logger.info("storeId=" + stores[i]);
                Store storeInDb = JSON.parseObject(merchantClient.thirdFindStoreById(stores[i]), Store.class);
                if (storeInDb == null) {
                    return new Result(StatusCode.ERROR, "第" + (i + 1) + "家店铺不存在");
                }
            }
        }

        //生效时间
        String validityStart = (String) jsonObject.get("validityStart") + "";
        if (!isValidDate(validityStart)) {
            return new Result(StatusCode.ERROR, "优惠券生效开始时间格式错误");
        }
        //结束时间
        String validityEnd = (String) jsonObject.get("validityEnd") + "";
        if (!isValidDate(validityEnd)) {
            return new Result(StatusCode.ERROR, "优惠券结束时间格式错误");
        }
        //新增优惠券
        Coupon coupon = new Coupon();
        coupon.setMemberId(memberId);
        coupon.setCompanyId(companyId);
        coupon.setStoreId(storeId);
        coupon.setStoreName(storeName);
        coupon.setPrice(BigDecimal.valueOf(price));
        coupon.setUsageCondition(usageCondition + "");
        coupon.setStatus("0");
        couponClient.thirdAddCouponByCoupon(JSON.toJSONString(coupon));
        return new Result(StatusCode.SUCCESS_INSERTED);
    }

    /**
     * 修改优惠券
     *
     * @param searchMap
     * @param id
     * @return
     */
    @RequestMapping(value = "updateCoupon/{id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result updateCoupon(@RequestBody String searchMap, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("searchMap=" + searchMap);
        Coupon couponInDb = JSON.parseObject(couponClient.thirdFindCouponById(id), Coupon.class);
        logger.info("couponInDb=" + couponInDb);
        if (couponInDb == null) {
            return new Result(StatusCode.ERROR, "该优惠券不存在");
        }
        if (couponInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR, "该优惠券已被删除");
        }

        JSONObject jsonObject = JSONObject.parseObject(searchMap);
        //会员id
        String memberId = jsonObject.get("memberId") + "";
        //body传的是String而不是map,所以nullValue.equals(memberId)代替memberId==null的判断
        if ("".equals(memberId) || nullValue.equals(memberId)) {
            logger.info("会员id不存在");
        } else {
            logger.info("会员id存在");
            //判断会员是否存在
            couponInDb.setMemberId(memberId);
        }
        //公司id
        String companyId = jsonObject.get("companyId") + "";
        if ("".equals(companyId) || nullValue.equals(companyId)) {
            logger.info("公司id不存在");
        } else {
            logger.info("公司id存在");
            //判断公司是否存在
            couponInDb.setCompanyId(companyId);
        }
        //店铺/商家id
        String storeId = jsonObject.get("storeId") + "";
        //店铺/商家名字
        String storeName = "";
        if ("".equals(storeId) || nullValue.equals(storeId)) {
            logger.info("店铺/商家id不存在");
        } else {
            //判断店铺/商家是否存在
            //店铺存在,则更新商家名字
            logger.info("店铺/商家id存在");
            couponInDb.setStoreId(storeId);
        }

        //面值
        String priceObject = jsonObject.get("price") + "";
        double price = 0.0;
        if ("".equals(priceObject) || nullValue.equals(priceObject)) {

        } else {
            price = Double.parseDouble(jsonObject.get("price") + "");
            //面值必须大于0
            if (price <= 0) {
                return new Result(StatusCode.ERROR, "面值必须大于0");
            }
            couponInDb.setPrice(BigDecimal.valueOf(price));
        }

        //使用条件 json值(price和stores)
        JSONObject usageCondition = jsonObject.getJSONObject("usageCondition");
        if ("".equals(usageCondition) || null == usageCondition) {

        } else {
            //判断使用条件中价格必须存在且大于等于0
            String priceTemp = usageCondition.get("price") + "";
            if ("".equals(priceTemp) || nullValue.equals(priceTemp)) {
                return new Result(StatusCode.ERROR, "使用条件中price必填");
            }
            double usageConditionPrice = Double.parseDouble(priceTemp);
            if (usageConditionPrice < 0) {
                return new Result(StatusCode.ERROR, "使用条件中price不能小于0");
            }
            couponInDb.setUsageCondition(usageCondition + "");

            //判断使用条件中店铺是否存在
            String usageConditionStores = (String) usageCondition.get("stores");
            if (usageConditionStores == null || "".equals(usageConditionStores)) {
//            return new Result(StatusCode.ERROR, "使用条件中store必填");
            } else {
                String[] stores = usageConditionStores.split(",");
                for (int i = 0; i < stores.length; i++) {
                    //判断店铺ID是否存在
                    logger.info("storeId=" + stores[i]);
                    Store storeInDb = JSON.parseObject(merchantClient.thirdFindStoreById(stores[i]), Store.class);
                    if (storeInDb == null) {
                        return new Result(StatusCode.ERROR, "第" + (i + 1) + "家店铺不存在");
                    }
                }
                couponInDb.setUsageCondition(usageCondition + "");
            }
        }
        //生效时间
        String validityStart = (String) jsonObject.get("validityStart") + "";
        logger.info("1111" + validityStart);
        logger.info("1111" + ("".equals(validityStart)));
        logger.info("1111" + (nullValue.equals(validityStart)));
        if (!"".equals(validityStart) && !nullValue.equals(validityStart)) {
            if (!isValidDate(validityStart)) {
                return new Result(StatusCode.ERROR, "优惠券生效开始时间格式错误");
            }

        }
        //结束时间
        String validityEnd = jsonObject.get("validityEnd") + "";
        if (!"".equals(validityEnd) && !nullValue.equals(validityEnd)) {
            if (!isValidDate(validityEnd)) {
                return new Result(StatusCode.ERROR, "优惠券结束时间格式错误");
            }
        }
        logger.info("------------" + couponInDb);
        couponClient.thirdUpdateCouponByCoupon(JSON.toJSONString(couponInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 删除优惠券
     *
     * @param id
     */
    @RequestMapping(value = "deleteCouponById/{id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result deleteCouponById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("id=" + id);

        Coupon couponInDb = JSON.parseObject(couponClient.thirdFindCouponById(id), Coupon.class);
        logger.info("couponInDb=" + couponInDb);
        if (couponInDb == null) {
            return new Result(StatusCode.ERROR, "该优惠券不存在");
        }
        if (couponInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR, "该优惠券已被删除");
        }

        couponInDb.setDeletedAt(LocalDateTime.now());
        couponClient.thirdUpdateCouponByCoupon(JSON.toJSONString(couponInDb));
        return new Result(StatusCode.SUCCESS_DELETED);
    }


    /**
     * 判断时间格式是否正确
     *
     * @param str
     * @return
     */
    public static boolean isValidDate(String str) {
        return true;
    }
}
